let questions = [];

window.addEventListener('message', (event) => {
    // 安全校验：可根据需要检查来源
    // if (event.origin !== 'https://your-domain.com') return;

    const {question_name, question_id} = event.data;


    window.name_question = question_name

    if (window.name_question) {
        document.getElementById('question-title').textContent = window.name_question;
    }
    loadQuestions()
});

async function loadQuestions() {


    const newData = {
        name: window.name_question
    };

    const res = await fetch("/api/ghq-questions/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            'X-CSRFToken': getCookie('csrftoken'),
        },
        body: JSON.stringify(newData),
        credentials: 'include',
    });

    const questions = await res.json();

    const container = document.getElementById("question-container");
    container.innerHTML = "";  // 清空旧内容
    window.questions = questions


    questions.forEach((q, index) => {
        const qDiv = document.createElement("div");
        qDiv.className = "question";

        const optionsHtml = q.options.map((opt, i) =>
            `<label><input type="radio" name="q${index}" value="${i}"> ${opt}</label>`
        ).join('');

        qDiv.innerHTML = `
            <label>${index + 1}. ${q.text}</label>
            <div class="options">${optionsHtml}</div>
        `;

        container.appendChild(qDiv);
    });
}


document.getElementById("ghq-form").addEventListener("submit", function (e) {
    e.preventDefault(); // 阻止默认提交

    let score = 0;
    let answers = [];

    for (let i = 0; i < window.questions.length; i++) {
        const val = document.querySelector(`input[name="q${i}"]:checked`);
        if (!val) {
            alert("请完成所有题目后再提交！");
            return;
        }

        const answer = parseInt(val.value);

        answers.push({
            code: window.questions[i].id,
            answer: answer
        });
    }

    // ✅ 将数据发送给父页面（交给父页面处理）
    window.parent.postMessage(
        {
            type: "ghq-data",
            data: {
                answers: answers
            }
        },
        "*"  // 建议替换为具体 origin
    );

    window.location.href = "completed";  // 可换成你实际的完成页路径

});

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// window.onload = loadQuestions;